import {Component} from 'react'
import {Breadcrumb, Button, FormControl, Select, Tree} from 'tinper-bee';
import CommonModal from './../../components/CommonModal/index.jsx';
import {vendorsDanger as danger, vendorsGetUrlParam} from 'utils/config.js';
import App from "../../layout/App";
import './index.less';

import {getBillList, getCreators, getOrgUrl, getProList, getSpecialExport} from './billsInquiry.config';
// 引入页面组件
import FormSearch from './FormSearch.jsx';
import TableBill from './TableBill.jsx';
// 导出报表公共方法
import exportExcel from './../../utils/exportExcel.js';

const Option = Select.Option;
const TreeNode = Tree.TreeNode;

let paramScope = 1;
let numberPerPage = 10; // 分页页数
let tenantId = document.cookie.split(';').find(cur => cur.indexOf('tenantid=') != -1).split('=')[1]; // 租户ID
// let tenantId = "x61tnmfx";
export default class BillsInquiry extends Component {
    constructor(props) {
        super(props);
        this.state = {
            orgName: "请选择111",
            params: null,   // 表单数据
            list: [],       // 单据列表
            proList: [],    // 项目列表
            items: 1,       // 表格分页：总页数
            activePage: 1,   // 表格分页：当前页
            showModal: false,
            searchValue: '',
            checkedKeys: [],
            orgTreeData: [],
            orgSearchText: '',
            normalOrgName: '默认组织名称',
            creators: [], // 制单人
            orgKey: '',
            pkOrg: '',
            billType: '', // 选择的单据类型
            showBreadcrumb: 2,
            showBreadFlag: false,
            nccStatus :false
        };
    }
    componentDidMount() {
        let searcharray = window.location.search.split('?')[1];
        let srcType = searcharray &&searcharray.length ?searcharray.split('&')[0] :[];
        let srcTypeArray = srcType && srcType.length ?srcType.split('=') :[];
        if(srcTypeArray.length  && srcTypeArray[0]==="pkSrc"){
            this.setState({
                nccStatus:true
            })
        }
        this.initPageData()
    }
    initPageData = () => {
        let fromGroupData = JSON.parse(sessionStorage.getItem('fromGroupData'));
        let startPage = vendorsGetUrlParam(decodeURI(window.location.href));
        startPage = Object.keys(startPage);
        if (fromGroupData && startPage && startPage.length) {
            let keysFromGroup = Object.keys(fromGroupData);
            if (keysFromGroup && keysFromGroup.length) {
                this.setState({
                    showBreadFlag: true,
                    proList: [{ sname: fromGroupData['projectName'], pkProject: fromGroupData['pkProject'] }]
                }, () => {
                    getOrgUrl().then((res) => {
                        if (res.data.resultCode !== 'busi_ex') {
                            let data = res.data.result;
                            getProList({ pkSrcOrg: fromGroupData['pk_org'] }).then((rest) => {
                                let { resultCode, result, exMsg } = rest.data;
                                if (resultCode !== "busi_ex") {
                                    this.setState({
                                        pkOrg: fromGroupData['pk_org'],
                                        normalOrgName: fromGroupData['orgName'],
                                        sname: fromGroupData['orgName'], // init data
                                        orgKey: fromGroupData['pk_org'],
                                        checkedKeys: [fromGroupData['pk_org']],
                                        checkName: fromGroupData['orgName'],
                                        orgTreeData: [data],
                                        showBreadcrumb: fromGroupData['showBreadcrumb'],
                                        proList: result
                                    });
                                } else {
                                    danger({ text: exMsg });
                                }
                            });
                        } else {
                            danger({ text: res.data.exMsg });
                        }
                    })
                });
            }
        } else {
            // 获取组织信息方法函数
            this.handlerGetOrgMethod();
        }
    }
    //获取组织信息
    handlerGetOrgMethod = () => {
        getOrgUrl().then((res) => {
            if (res.data.resultCode !== 'busi_ex') {
                let data = res.data.result;
                let pkSrcOrg = data.pkTenant;
                getProList({ pkSrcOrg }).then((rest) => {
                    // getProList({ pkSrcOrg: '00013A100000000064S5' }).then((rest) => {
                    let { resultCode, result, exMsg } = rest.data;
                    if (resultCode !== "busi_ex") {
                        this.setState({
                            normalOrgName: data.sname,
                            sname: data.sname, // init data
                            orgKey: data.pkTenant,
                            pkTenant: data.pkTenant, // init data
                            orgTreeData: [data],
                            proList: result
                        });
                    } else {
                        danger({ text: exMsg });
                        this.setState({
                            normalOrgName: data.sname,
                            sname: data.sname, // init data
                            orgKey: data.pkTenant,
                            pkTenant: data.pkTenant, // init data
                            orgTreeData: [data]
                        });
                    }
                });
            } else {
                danger({ text: res.data.exMsg });
            }
        })
    }

    //获取制单人
    getBillsCreators = (pkPro) => {
        let pkProject = pkPro === '请选择' ? null : pkPro;
        getCreators({ pkProject }).then((res) => {
            let { resultCode, result, exMsg } = res.data;
            if (resultCode !== "busi_ex") {
                this.setState({
                    creators: result
                });
            } else {
                danger({ text: exMsg });
            }
        });
    }

    //选择组织
    handleOrganizationSelect = (value) => {
        this.setState({
            showModal: true
        });
    }

    //隐藏组织弹框
    onhide = () => {
        this.setState({
            showModal: false
        });
    }

    //模态框确认逻辑
    handlerModalConfirm = () => {
        this.setState({
            showModal: false,
            normalOrgName: this.state.checkName
        }, () => {
            getProList({ pkSrcOrg: this.state.orgKey }).then((res) => {
                let { resultCode, result, exMsg } = res.data;
                if (resultCode !== "busi_ex") {
                    this.setState({
                        proList: result
                    });
                } else {
                    danger({ text: exMsg });
                }
            });
        });
    }

    handlerOrgSearchText = (e) => {
        let value = e.target.value;
        this.setState({
            orgSearchText: value
        });
    }

    // 组织模态框内容
    getModalContext = () => {
        return (
            <div>
                <div className="clearfix">
                    <FormControl
                        size="lg"
                        className="fl org--search"
                        placeholder="请输入名称"
                        onChange={this.handlerOrgSearchText}
                    />
                    <a href="javascript:;" className="org--search__btn fl" onClick={this.handlerChooseOrgBtn}></a>
                </div>
                <Tree checkable
                    checkStrictly
                    onCheck={this.onCheck}
                    checkedKeys={this.state.checkedKeys}
                >
                    {this.loop(this.state.orgTreeData)}
                </Tree>
            </div>
        )
    }

    // 选择树节点
    onCheck = (checkedKeys, e) => {
        if (e.node.props.eventKey !== 'null') {
            paramScope = 0;
        } else {
            paramScope = 1;
        }
        let checkedKey = checkedKeys.pop();
        checkedKeys = [];
        checkedKeys.push(checkedKey);
        let checkName = e.node.props.title.props.children[0] + e.node.props.title.props.children[1].props.children + e.node.props.title.props.children[2];
        let normalOrgName = "";
        if (checkedKey === "null" || checkedKey === undefined) {
            normalOrgName = this.state.sname;
        } else {
            normalOrgName = checkName;
        }
        this.setState({
            checkedKeys,
            orgKey: checkedKey === "null" || checkedKey === undefined ? this.state.pkTenant : checkedKey,
            checkName: normalOrgName
        });
    }

    // 遍历树节点
    loop = data => data.map((item) => {
        if (item.sname) { // 集成diwork后，该值在初始化时为null，需要做一步判断
            const index = item.sname.search(this.state.searchValue);
            const beforeStr = item.sname.substr(0, index);
            const afterStr = item.sname.substr(index + this.state.searchValue.length);
            const title = index > -1 ? (
                <span>
                    {beforeStr}
                    <span className="u-tree-searchable-filter">{this.state.searchValue}</span>
                    {afterStr}
                </span>
            ) : <span>{item.sname}</span>

            if (item.children && item.children.length) {
                return <TreeNode key={item.pkSrc} title={title}>{this.loop(item.children)}</TreeNode>;
            }
            return <TreeNode key={item.pkSrc} title={title} />;
        }
    })

    // 选择组织
    handlerChooseOrgBtn = () => {
        this.setState({
            searchValue: this.state.orgSearchText
        });
        // 定位树节点
        setTimeout(() => {
            document.getElementsByClassName("u-tree-searchable-filter")[0].scrollIntoView();
        }, 0);
    }

    //搜索单据..
    searchBillList = (param) => {
        let pageStart = param.activePage ? param.activePage : 1;
        if (param.billType === null) {
            danger({ text: '单据类型不能为空' });
        } else {
            let postData = {
                "pkOrg": this.state.orgKey,
                "billStatus": param.billStatus,
                "billType": param.billType,
                "startTime": param.startTime,
                "endTime": param.endTime,
                "creators": param.creators,
                "pkProject": param.pkProject,
                "pageStart": numberPerPage * (pageStart - 1),
                "pageSize": numberPerPage
            };
            getBillList(postData).then((res) => {
                if (res.data.resultCode !== 'busi_ex') {
                    let list = res.data.result.objects;
                    let pages = Math.ceil(res.data.result.count / numberPerPage);
                    this.setState({
                        params: postData,
                        list: list,
                        items: pages,
                        activePage: pageStart
                    });
                } else {
                    let text = res.data.exMsg;
                    danger({ text: text });
                }
            });
        }
    }

    // 展示组织选择框
    handleOrganizeChange = () => {
        this.setState({
            showModal: true,
            searchValue: ''
        });
    }

    // 亿嘉和专项导出模板功能 只有租户ID为亿嘉和，且查询类型为巡查记录或施工记录时，才会显示导出按钮执行该方法
    exportTemp = () => {
        let postData = JSON.parse(localStorage.getItem('searchPostData'));
        postData.pkOrg = this.state.orgKey;
        getSpecialExport(postData).then((res) => {
            let { exMsg, resultCode } = res.data;
            if (resultCode == "busi_ex") {
                danger({ text: exMsg });
            } else {
                let { billType } = postData;
                let filename = ""; // 导出的文件名
                switch (billType) {
                    case 'XCJL':
                        filename = "安全文明巡查表";
                        break;
                    case 'SGJL':
                        filename = "施工记录检查表";
                        break;
                    default:
                        break;
                }
                exportExcel(res.data, filename);
            }
        });
    }

    // 每次切换单据类型后，整理当前单据类型数据和搜索数据到state
    setSearchParams = (params) => {
        localStorage.setItem('searchPostData', JSON.stringify(params)); // 修改表头信息后，不更改state的搜索信息，否则表格渲染会受到影响
        this.setState({billType: params.billType});
    }

    //分页搜索单据
    handleSelectPage = (e) => {
        this.setState({
            activePage: e
        });
        this.searchBillList({ activePage: e, ...this.state.params });
    }

    render() {
        let { showBreadFlag, showBreadcrumb, billType, nccStatus } = this.state;
        let isShowExportButton = false;
        /* ga6oqeyu 亿嘉和*/
        if (tenantId === 'ga6oqeyu' && (billType === 'XCJL' || billType === 'SGJL')) {
            isShowExportButton = true;
        } else {
            isShowExportButton = false;
        }

        let searcharray = window.location.search.split('?')[1];
        let srcType = searcharray &&searcharray.length ?searcharray.split('&')[0] :[];
        let srcTypeArray = srcType && srcType.length ?srcType.split('=') :[];
        let projectboardHref = ''
        if(srcTypeArray[0] === "pkSrc" && srcTypeArray[1]){
            projectboardHref=`/projectboard.html?pkSrc=${srcTypeArray[1]}`
        }else{
            projectboardHref="/projectboard.html"
        }
       
        return (
            <App>
                <CommonModal
                    show={this.state.showModal}
                    confirm={this.handlerModalConfirm}
                    content={this.getModalContext()}
                    hide={this.onhide}
                    backdrop={true}
                    size={'lg'}
                    title={'选择组织'}
                    oneButton={true}
                    oneButtonText={'确定'}
                >
                </CommonModal>
                <div className="bill">
                    <div className="bill-header padding-left10">
                        {showBreadFlag ?
                            <div className="brc-nav">
                                 {showBreadcrumb == 4 ?
                                      <Breadcrumb>
                                      
                                        {!nccStatus ? 
                                            <Breadcrumb.Item href='/workfile.html'>
                                                    项目档案
                                            </Breadcrumb.Item> : null}
                                        <Breadcrumb.Item href={projectboardHref}  >
                                                进度看板
                                        </Breadcrumb.Item>
                                        <Breadcrumb.Item active>
                                                单据查询列表
                                        </Breadcrumb.Item>
                                      </Breadcrumb>
                                        : 
                                        <Breadcrumb>
                                            {showBreadcrumb == 3 ?
                                                <Breadcrumb.Item href='/groupquery.html?page_state=1'>
                                                    集团查看
                                            </Breadcrumb.Item> : null}
                                            <Breadcrumb.Item href='/dataanalysis.html?page_state=1'>
                                                企业看板
                                            </Breadcrumb.Item>
                                        
                                        
                                            <Breadcrumb.Item active>
                                                单据查询列表
                                            </Breadcrumb.Item>
                                    </Breadcrumb>
                                }
                               
                            </div> : <span className="bill-header-title">
                                单据查询列表
                        </span>}
                    </div>
                    <div className="bill-body padding10">
                        <div className="bill-body-org">
                            <span className="fl bill-body-org-title">{this.state.normalOrgName}</span>
                            {!showBreadFlag ? <Button className="fl organize--btn" colors="primary" onClick={this.handleOrganizeChange}>切换组织</Button> : null}
                            {isShowExportButton ? <Button className="fr organize--btn" colors="primary" onClick={this.exportTemp}>导出列表</Button> : null}
                        </div>
                        <FormSearch
                            billType={this.state.billType}
                            searchBillList={this.searchBillList}
                            activePage={this.state.activePage}
                            creators={this.state.creators}
                            proList={this.state.proList}
                            orgName={this.state.normalOrgName}
                            getCreators={this.getBillsCreators}
                            setSearchParams={this.setSearchParams}
                        />
                        <TableBill
                            items={this.state.items}
                            activePage={this.state.activePage}
                            data={this.state.list}
                            type={this.state.params ? this.state.params.billType : null}
                            handleSelectPage={this.handleSelectPage}
                        />
                    </div>
                    <div className="bill-footer"></div>
                </div>
            </App>
        );
    }
}